package logic

import (
	"context"
	"database/sql"
	"github.com/dtm-labs/dtmcli"
	"github.com/dtm-labs/dtmgrpc"
	"go-zero-project/services/order/rpc/internal/mapper"
	"go-zero-project/services/order/rpc/internal/mapper/entity"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"

	"go-zero-project/services/order/rpc/internal/svc"
	"go-zero-project/services/order/rpc/pb"

	"github.com/zeromicro/go-zero/core/logx"
)

type CreateLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewCreateLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreateLogic {
	return &CreateLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *CreateLogic) Create(in *pb.CreateRequest) (*pb.CreateResponse, error) {
	// 1.获取子事务屏障对象
	branchBarrier, err := dtmgrpc.BarrierFromGrpc(l.ctx)
	if err != nil {
		return nil, err
	}
	// 2.开启子事务屏障
	dbEngin := l.svcCtx.DBEngin
	db, err := dbEngin.DB()
	if err != nil {
		return nil, err
	}
	err = branchBarrier.CallWithDB(db, func(tx *sql.Tx) error {
		// 创建订单
		newOrder := entity.OrderEntity{
			Id:     in.OrderId,
			Uid:    in.Uid,
			Pid:    in.Pid,
			Amount: int(in.Amount),
			Status: 0,
		}
		orderMapper := mapper.NewOrderMapper()
		insertResult, insertResultErr := orderMapper.TxInsert(l.ctx, tx, &newOrder)
		if insertResultErr != nil {
			return insertResultErr
		}
		// 处理失败,返回子事务失败
		affected, err := insertResult.RowsAffected()
		// 处理失败，返回子事务失败
		if err == nil && affected == 0 {
			return dtmcli.ErrFailure
		}
		return err
	})
	if err == dtmcli.ErrFailure {
		return nil, status.Error(codes.Aborted, dtmcli.ResultFailure)
	}
	if err != nil {
		return nil, err
	}
	return &pb.CreateResponse{}, nil
}
